﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yto.Entities.Record;

namespace com.ytocargo.Core.BackgroundJobInfos
{
    [Table("YTO_BACKGROUNDJOB")]
    public class BackgroundJobInfo : FullEntity
    {
        [Required]
        [StringLength(512)]
        public virtual string JobType { get; set; }

        [Required]
        [StringLength(1024*1024)]
        public virtual string JobArgs { get; set; }

        public virtual short TryCount { get; set; }

        public virtual DateTime NextTryTime { get; set; }

        public virtual DateTime? LastTryTime { get; set; }

        public virtual bool IsAbandoned { get; set; }

        public virtual BackgroundJobPriority Priority { get; set; }


        const int DEFAULT_DURATION = 60;
        const double DEFAULT_FACTOR = 2.0;
        const int DEFAULT_TIMEOUT = 172800;


        public  virtual DateTime? CaculateNextTry()
        {
            var duration = DEFAULT_DURATION * (Math.Pow(DEFAULT_FACTOR, TryCount - 1));
            var nextTryTime = LastTryTime.HasValue ? LastTryTime.Value.AddSeconds(duration)
                : DateTime.Now.AddSeconds(duration);

            if (nextTryTime.Subtract(CreateTime).TotalSeconds > DEFAULT_TIMEOUT)
            {
                return null;
            }
            return nextTryTime;
        }
    }
}
